<template>
  <el-container class="content">
    <el-aside width="200px" v-loading="showGrouploading">
      <el-container>
        <el-header>
          <el-input placeholder="输入关键字进行过滤" v-model="groupFilterText" clearable></el-input>
        </el-header>
        <el-main class="nopadding">
          <el-tree ref="group" class="menu" node-key="id" :data="group" :current-node-key="''"
                   :highlight-current="true" :expand-on-click-node="false"
                   :filter-node-method="groupFilterNode" @node-click="groupClick"></el-tree>
        </el-main>
      </el-container>
    </el-aside>
    <el-container>
      <el-header>
        <div class="left-panel">
          <el-button type="primary" :icon="plus" @click="showRegister"></el-button>
          <el-button type="danger" plain :icon="deleteIcon" :disabled="selection.length==0"
                     @click="batch_del"></el-button>
          <el-button type="primary" plain :disabled="selection.length===0">分配角色</el-button>
          <el-button type="primary" plain :disabled="selection.length!==1" @click="showRestPassword">密码重置
          </el-button>
        </div>
        <div class="right-panel">
          <div class="right-panel-search">
            <el-input v-model="searchObject.name" placeholder="登录账号 / 姓名" clearable></el-input>
            <el-button type="primary" :icon="searchIcon" @click="upsearch" style="margin-left: 10px;"></el-button>
          </div>
        </div>
      </el-header>
      <el-main class="nopadding">
        <el-table ref="table" @selection-change="selectionChange" v-loading="loading" :data="tableData.data"
                  @sort-change="changeTableSort"
                  style="width: 100%;font-size: 12px;">
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="ID" prop="id" width="80" sortable='custom'></el-table-column>
          <el-table-column label="头像" width="80" column-key="filterAvatar"
                           :filters="[{text: '已上传', value: '1'}, {text: '未上传', value: '0'}]">
            <template #default="scope">
              <el-avatar :src="scope.row.avatar" size="small"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="登录账号" prop="accountNo" width="180"></el-table-column>
          <el-table-column label="姓名" prop="name" width="150" sortable='custom'></el-table-column>
          <el-table-column label="所属部门" prop="structureName" width="200"></el-table-column>
          <el-table-column label="数据权限" prop="dataScopeName" width="170"></el-table-column>
          <el-table-column label="加入时间" prop="addDate"></el-table-column>
          <el-table-column label="操作" fixed="right" align="center" width="160">
            <template #default="scope">
              <el-button-group>
                <el-button text type="primary" size="small"
                           @click="table_show(scope.row, scope.$index)">查看
                </el-button>
                <el-button text type="primary" size="small"
                           @click="table_edit(scope.row, scope.$index)">编辑
                </el-button>
                <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
                  <template #reference>
                    <el-button text type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </el-button-group>
            </template>
          </el-table-column>

        </el-table>
        <div class="page">
          <el-pagination background :current-page="searchObject.no" :page-sizes="[10, 20, 50, 100]"
                         :page-size="tableData.size" :pager-count="5"
                         layout="total, sizes, prev, pager, next, jumper" :page-count="tableData.totalPage"
                         :total="tableData.total" @size-change="sizeChange" @current-change="pageChange">
          </el-pagination>
        </div>
      </el-main>
    </el-container>
  </el-container>

  <save-dialog v-if="dialog.save" ref="saveDialog" @success="handleSuccess" @closed="dialog.save=false"></save-dialog>
  <el-dialog title="重置密码" v-model="restPasswordVisible" width="30%">
    <el-form :model="form" :rules="rules" label-width="100px" ref="dialogForm"
             label-position="left">
      <el-form-item label="登录密码" prop="restPassword">
        <el-input v-model="form.restPassword" placeholder="请输入登录密码" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="restPasswordVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleRestPassword">确 定</el-button>
        </span>
    </template>
  </el-dialog>

  <el-dialog title="添加账号" v-model="registerVisible" width="30%">
    <el-form :model="registerForm" :rules="registerRules" label-width="100px" ref="registerForm"
             label-position="left">
      <el-form-item label="用户账号" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入账号" clearable></el-input>
      </el-form-item>
      <el-form-item label="登录密码" prop="password">
        <el-input v-model="registerForm.password" placeholder="请输入登录密码" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
        <span class="dialog-footer">
          <el-button @click="registerVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleRegister">确 定</el-button>
        </span>
    </template>
  </el-dialog>


</template>

<script>
import saveDialog from './save.vue'
import {Delete, Edit, Plus, Search} from "@element-plus/icons-vue";

export default {
  name: 'user',
  components: {
    saveDialog
  },
  data() {
    return {
      dialog: {
        save: false
      },
      showGrouploading: false,
      form: {
        restPassword: ""
      },
      registerForm: {
        username: "",
        password: "",
        accountType: "phone"
      },
      plus: Plus,
      Edit: Edit,
      deleteIcon: Delete,
      searchIcon: Search,
      searchObject: {
        no: 1,
        size: 10,
        sortField: "id",
        sortMethod: "desc",
        personnel: ''
      },
      dialogVisible: false,
      restPasswordVisible: false,
      registerVisible: false,
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      loading: false,
      tableData: {
        size: 0,
        total: 0,
        totalPage: 0,
        data: []
      },
      personnelOptions: [],
      groupFilterText: '',
      group: [],
      apiObj: "staff/search",
      selection: [],
      search: {
        name: null
      },
      rules: {
        restPassword: [
          {required: true, message: '请输入密码'}
        ]
      },
      registerRules: {
        username: [
          {required: true, message: '请输入用户名'}
        ],
        password: [
          {required: true, message: '请输入密码'}
        ]
      }
    }
  },
  watch: {
    groupFilterText(val) {
      this.$refs.group.filter(val);
    }
  },
  mounted() {
    this.getGroup()
    this.getSearchList();
  },
  methods: {
    //添加
    add() {
      this.dialog.save = true
      this.$nextTick(() => {
        this.$refs.saveDialog.open()
      })
    },
    showRestPassword() {
      this.restPasswordVisible = true;
    },
    showRegister() {
      this.registerVisible = true;
    },
    async handleRestPassword() {
      let self = this;
      let password = {};
      password.id = this.selection[0].id;
      password.password = this.form.restPassword;
      await this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          let res = await this.$http.post("/userInfo/resetPassword", password);
          if (res.code === 200) {
            self.$message.success("重置密码成功")
            self.restPasswordVisible = false;
          } else {
            await self.$alert(res.msg, "提示", {type: 'error'})
          }
        } else {
          return false;
        }
      })
    },
    async handleRegister() {
      let self = this;
      await this.$refs.registerForm.validate(async (valid) => {
        if (valid) {
          let res = await this.$http.post("/user/register", self.registerForm);
          if (res.code === 200) {

            if (res.data.id) {
              let userForm = {};
              userForm.id = res.data.id;
              if (self.searchObject.structure) {
                userForm.structure = self.searchObject.structure;
                userForm.dataScope = "myDepartment";
                await self.$http.post(`/userInfo/update`, userForm);
              }
            }
            self.$message.success("添加账号成功")
            await self.getSearchList();
            self.registerVisible = false;
          } else {
            await self.$alert(res.msg, "提示", {type: 'error'})
          }
        } else {
          return false;
        }
      })
    },
    async getSearchList() {
      this.loading = true;
      let data = this.searchObject;
      let res = await this.$http.post("/userInfo/search", data);
      if (res.code === 200) {
        this.tableData = res;
      }
      this.loading = false;
      this.$tool.data.set("salary_search", this.searchObject);

    },
    //编辑
    table_edit(row) {
      this.dialog.save = true
      this.$nextTick(() => {
        this.$refs.saveDialog.open('update').setData(row)
      })
    },
    //查看
    table_show(row) {
      this.dialog.save = true
      this.$nextTick(() => {
        this.$refs.saveDialog.open('show').setData(row)
      })
    },
    //删除
    async table_del(row, index) {
      const reqData = {id: row.id};
      const res = await this.$http.post(`/userInfo/delete`, reqData);
      if (res.code === 200) {
        await this.getSearchList();
        this.$message.success("删除成功")
      } else {
        await this.$alert(res.msg, "提示", {type: 'error'})
      }
    },
    //批量删除
    async batch_del() {
      try {
        await this.$confirm(`确定删除选中的 ${this.selection.length} 项吗？`, '提示', {
          type: 'warning'
        });

        const loading = this.$loading();
        for (const item of this.selection) {
          const res = await this.$http.post(`/userInfo/delete`, item);
          if (res.code !== 200) {
            await this.$alert(res.msg, "提示", {type: 'error'})
            loading.close();
            return;
          }
        }
        await this.getSearchList();
        loading.close();
        this.$message.success("操作成功")
      } catch (e) { /* empty */
      }


    },
    //表格选择后回调事件
    selectionChange(selection) {
      this.selection = selection;
    },
    //加载树数据
    async getGroup() {
      this.showGrouploading = true;
      let res = await this.$http.post(`/structure/list`, {depth: 1, fetch: 1});
      this.showGrouploading = false;
      if (res.code !== 200 || res.data === null) {
        return;
      }
      const allNode = {id: '', label: '所有'};
      res.data.unshift(allNode);
      this.group = res.data;
    },
    //树过滤
    groupFilterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    //树点击事件
    groupClick(data) {
      this.searchObject.structure = data.id;
      this.getSearchList();
    },
    //搜索
    upsearch() {
      this.getSearchList();
    },
    //本地更新数据
    handleSuccess(data, mode) {
      if (mode === 'create') {
        data.id = new Date().getTime()
        this.getSearchList();
      } else if (mode === 'update') {
        this.getSearchList();
      }
    },
    sizeChange(event) {
      this.searchObject.size = event;
      this.getSearchList();
    },
    pageChange(index) {
      this.searchObject.no = index;
      this.getSearchList();
    },
    search() {
      this.searchObject.no = 1;
      this.getSearchList();
    },
    changeTableSort(column) {
      this.searchObject.sortField = column.prop;
      if ("descending" === column.order) {
        this.searchObject.sortMethod = "desc";
      } else if ("ascending" === column.order) {
        this.searchObject.sortMethod = "asc";
      } else {
        this.searchObject.sortMethod = "";
      }
      this.getSearchList();
    }
  }
}
</script>

<style>
.content {
  background-color: #fff;
  padding: 15px 5px;
}

.el-header {
  background: #fff;
  border-bottom: 1px solid var(--el-border-color-light);
  padding: 13px 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-panel-search {
  display: flex;
  align-items: center;
}
</style>
